package handler

import (
	"net/http"

	"markedit/internal/middleware"
	"markedit/internal/model"
	"markedit/internal/service"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type UserFileHandler struct {
	userFileService *service.UserFileService
	logger          *logrus.Logger
}

func NewUserFileHandler(userFileService *service.UserFileService, logger *logrus.Logger) *UserFileHandler {
	return &UserFileHandler{
		userFileService: userFileService,
		logger:          logger,
	}
}

// CreateFile 创建文件或文件夹
func (h *UserFileHandler) CreateFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	var req model.UserFileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	// 验证必填字段
	if req.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件名不能为空",
		})
		return
	}

	file, err := h.userFileService.CreateFile(userID, &req)
	if err != nil {
		h.logger.Errorf("创建文件失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户 %s 创建文件: %s", userID, file.Name)
	c.JSON(http.StatusCreated, gin.H{
		"message": "创建成功",
		"file": gin.H{
			"id":        file.ID,
			"name":      file.Name,
			"path":      file.Path,
			"is_folder": file.IsFolder,
			"size":      file.Size,
			"mime_type": file.MimeType,
			"created_at": file.CreatedAt,
		},
	})
}

// GetFile 获取文件内容
func (h *UserFileHandler) GetFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	fileID := c.Param("id")
	if fileID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件ID不能为空",
		})
		return
	}

	file, err := h.userFileService.GetFile(userID, fileID)
	if err != nil {
		h.logger.Errorf("获取文件失败: %v", err)
		c.JSON(http.StatusNotFound, gin.H{
			"error": err.Error(),
		})
		return
	}

	response := gin.H{
		"id":         file.ID,
		"name":       file.Name,
		"path":       file.Path,
		"size":       file.Size,
		"mime_type":  file.MimeType,
		"is_folder":  file.IsFolder,
		"parent_id":  file.ParentID,
		"created_at": file.CreatedAt,
		"updated_at": file.UpdatedAt,
	}

	// 只有非文件夹才返回内容
	if !file.IsFolder {
		response["content"] = file.Content
	}

	c.JSON(http.StatusOK, response)
}

// UpdateFile 更新文件内容
func (h *UserFileHandler) UpdateFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	fileID := c.Param("id")
	if fileID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件ID不能为空",
		})
		return
	}

	var req struct {
		Content string `json:"content"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	file, err := h.userFileService.UpdateFile(userID, fileID, req.Content)
	if err != nil {
		h.logger.Errorf("更新文件失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户 %s 更新文件: %s", userID, file.Name)
	c.JSON(http.StatusOK, gin.H{
		"message": "更新成功",
		"file": gin.H{
			"id":         file.ID,
			"name":       file.Name,
			"path":       file.Path,
			"size":       file.Size,
			"updated_at": file.UpdatedAt,
		},
	})
}

// DeleteFile 删除文件
func (h *UserFileHandler) DeleteFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	fileID := c.Param("id")
	if fileID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件ID不能为空",
		})
		return
	}

	err := h.userFileService.DeleteFile(userID, fileID)
	if err != nil {
		h.logger.Errorf("删除文件失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户 %s 删除文件: %s", userID, fileID)
	c.JSON(http.StatusOK, gin.H{
		"message": "删除成功",
	})
}

// RenameFile 重命名文件
func (h *UserFileHandler) RenameFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	fileID := c.Param("id")
	if fileID == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件ID不能为空",
		})
		return
	}

	var req struct {
		Name string `json:"name"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	if req.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件名不能为空",
		})
		return
	}

	file, err := h.userFileService.RenameFile(userID, fileID, req.Name)
	if err != nil {
		h.logger.Errorf("重命名文件失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	h.logger.Infof("用户 %s 重命名文件: %s", userID, file.Name)
	c.JSON(http.StatusOK, gin.H{
		"message": "重命名成功",
		"file": gin.H{
			"id":   file.ID,
			"name": file.Name,
			"path": file.Path,
		},
	})
}

// ListFiles 列出文件
func (h *UserFileHandler) ListFiles(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	parentID := c.Query("parent_id")
	
	files, err := h.userFileService.ListFiles(userID, parentID)
	if err != nil {
		h.logger.Errorf("列出文件失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"files": files,
	})
}

// GetFileTree 获取文件树
func (h *UserFileHandler) GetFileTree(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	tree, err := h.userFileService.GetFileTree(userID)
	if err != nil {
		h.logger.Errorf("获取文件树失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"tree": tree,
	})
}

// SearchFiles 搜索文件
func (h *UserFileHandler) SearchFiles(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	keyword := c.Query("keyword")
	if keyword == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "搜索关键词不能为空",
		})
		return
	}

	files, err := h.userFileService.SearchFiles(userID, keyword)
	if err != nil {
		h.logger.Errorf("搜索文件失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"files": files,
		"keyword": keyword,
	})
}

// SaveFile 保存文件到账户空间
func (h *UserFileHandler) SaveFile(c *gin.Context) {
	userID, exists := middleware.GetUserID(c)
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"error": "未登录",
		})
		return
	}

	var req struct {
		Name     string `json:"name"`
		Content  string `json:"content"`
		ParentID string `json:"parent_id"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "请求参数错误",
			"details": err.Error(),
		})
		return
	}

	if req.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "文件名不能为空",
		})
		return
	}

	// 检查文件是否已存在，如果存在则更新，否则创建
	existingFile, err := h.userFileService.GetFileByPath(userID, "/"+req.Name)
	if err == nil {
		// 文件存在，更新内容
		file, err := h.userFileService.UpdateFile(userID, existingFile.ID, req.Content)
		if err != nil {
			h.logger.Errorf("更新文件失败: %v", err)
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		h.logger.Infof("用户 %s 更新文件: %s", userID, file.Name)
		c.JSON(http.StatusOK, gin.H{
			"message": "文件保存成功",
			"action":  "updated",
			"file": gin.H{
				"id":   file.ID,
				"name": file.Name,
				"path": file.Path,
				"size": file.Size,
			},
		})
	} else {
		// 文件不存在，创建新文件
		fileReq := &model.UserFileRequest{
			Name:     req.Name,
			Content:  req.Content,
			ParentID: req.ParentID,
			IsFolder: false,
		}

		file, err := h.userFileService.CreateFile(userID, fileReq)
		if err != nil {
			h.logger.Errorf("创建文件失败: %v", err)
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		h.logger.Infof("用户 %s 创建文件: %s", userID, file.Name)
		c.JSON(http.StatusCreated, gin.H{
			"message": "文件保存成功",
			"action":  "created",
			"file": gin.H{
				"id":   file.ID,
				"name": file.Name,
				"path": file.Path,
				"size": file.Size,
			},
		})
	}
}